#!usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
import hmac
import base64
import requests
import json


class ProxyFactory(object):
    def __init__(self):
        self.method = 'GET'  # 请求方式
        self.endpoint = 'dev.kdlapi.com/api/getorderexpiretime'
        self.username = "chuanxuelove@163.com"
        self.password = "xinrui0903"
        self.secret_id = "ul4yo4fw2cpls50sta6g"
        self.secret_key = "rmmlaqg4bin5v3q07ovts0sgqw73bx1d"
        self.proxy_api_format = "https://dps.kdlapi.com/api/getdps/?secret_id=ul4yo4fw2cpls50sta6g&signature=xxxxx&num=1&pt=1&sep=1"

    """用于保存用户secret_id、secret_key，以及计算签名的对象。"""
    # def __init__(self, secret_id, secret_key):
    #     self.secret_id = secret_id
    #     self.secret_key = secret_key

    @classmethod
    def get_string_to_sign(cls, method, endpoint, params):
        """ 生成签名原文字符串 """
        s = method + endpoint.split('.com')[1] + '?'
        query_str = '&'.join("%s=%s" % (k, params[k]) for k in sorted(params))
        return s + query_str

    def sign_str(self, raw_str, method=hashlib.sha1):
        """ 生成签名串 """
        try:
            hmac_str = hmac.new(self.secret_key.encode('utf8'), raw_str.encode('utf8'), method).digest()
        except UnicodeDecodeError as e:
            hmac_str = hmac.new(self.secret_key.encode('utf8'), raw_str, method).digest()
        return base64.b64encode(hmac_str)


def _get_base_res(method, endpoint, params):
    """处理基础请求,
       若响应为json格式则返回请求结果dict
       否则直接返回原格式
    """
    try:
        r = None
        if method == "GET":
            r = requests.get("https://" + endpoint, params=params)
        elif method == "POST":
            r = requests.post("https://" + endpoint, data=params)
        if r.status_code != 200:
            return 'HTTP Status Code: %s' % r.status_code
        try:
            return json.loads(r.content.decode('utf8'))
        except ValueError as e:  # 返回结果不是json格式, 直接返回
            return r.content.decode('utf8')
    except Exception as e:
        print(str(e))


if __name__ == '__main__':
    secret_id = 'o1fjh1re9o28876h7c08'
    secret_key = 'jd1gzm6ant2u7pojhbtl0bam0xpzsm1c'
    method = 'GET'  # 请求方式
    endpoint = 'dev.kdlapi.com/api/getorderexpiretime'
    # 除signature外的所有参数都放入params
    params = {
        'secret_id': secret_id,
        'sign_type': 'hmacsha1',
        'timestamp': int(time.time()),
    }

    auth = Auth(secret_id, secret_key)
    raw_str = auth.get_string_to_sign(method, endpoint, params)
    params['signature'] = auth.sign_str(raw_str)
    res = _get_base_res(method, endpoint, params)
    print(res)